#coding:utf8

from libjade import *
nt= (os.name=='nt')

tpl_cmake_file='''cmake_minimum_required(VERSION 2.6)
project(jadesoul)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")

#add_subdirectory
%s

#include_directories
%s

#for each target
%s
'''

tpl_add_subdirectory='add_subdirectory(%s)'

tpl_include_directories='include_directories(%s)'

tpl_target='''add_executable(%s %s.cpp)
add_custom_command(
	TARGET %s
	POST_BUILD
	COMMAND python ${CMAKE_SOURCE_DIR}/scripts/move_target.py ${CMAKE_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} %s
	COMMENT "Postbuild action : move target %s"
)'''

def gen_cmake_recursively(tests_root, rel_base):
	root=tests_root
	dirs=[]
	files=[]
	for fn in listdir(root):
		fp=join(root, fn)
		if isfile(fp): files.append(fn)
		elif isdir(fp) and fn[0]!='.': 
			gen_cmake_recursively(fp, '../'+rel_base)
			dirs.append(fn)
			
	fp_cmake=join(root, 'CMakeLists.txt')
	
	s_add_subdirectory='\n'.join([tpl_add_subdirectory % (i if nt else i+' '+i+'_dir') for i in dirs if i[0]!='.'])
	s_include_directories=tpl_include_directories % rel_base
	targets=[]
	for fn in files:
		fp=join(root, fn)
		if len(fn)>4 and fn.endswith('.cpp'):
			target_name=fn[:-4]
			targets.append(tpl_target % ((target_name,) * 5))
	s_targets='\n\n'.join(targets)
	s_cmake=tpl_cmake_file % (s_add_subdirectory, s_include_directories, s_targets)

	if not ( isfile(fp_cmake) and fread(fp_cmake)==s_cmake ):
		fwrite(s_cmake, fp_cmake)
		print 'generated:', fp_cmake
